<template>
  <div class="main">
    <div id="userinfo" class="container">
      <h3 class="title" style="color: gray">系统使用说明</h3>
      <h4 class="title" style="color: cornflowerblue">下方表格的内容即是自动提交的内容，请认真填写，请认真填写,欢迎加入QQ交流群，获取最新通知：872185037</h4>
      <h6 class="title" style="color: yellowgreen">本系统只是为了防止大家忘记，也方便减轻班长，辅导员的工作量，如果身体异常记得关闭服务，同时联系辅导员</h6>
      <el-row>
        <el-col :span="2" :offset="1">
          <el-button type="success" size="small" plain @click="pop()" :disabled="BtDisable.pop"
                     style="font-size: 14px;">剩余天数</el-button>
        </el-col>
        <el-col :span="2" :offset="6">
          <el-button type="success" size="small" plain @click="showbind()" :disabled="BtDisable.bind"
                     style="font-size: 14px;">更改绑定</el-button>
        </el-col>
        <el-col :span="2" :offset="6">
          <el-button type="success" size="small" plain @click="showemail()" :disabled="BtDisable.email"
                     style="font-size: 14px;">验证邮箱</el-button>
        </el-col>
      </el-row>
      <br/>
      <el-row>
        <el-col :span="2" :offset="5">
          <el-button type="success" size="small" plain @click="showtopup()" :disabled="BtDisable.topup"
                     style="font-size: 14px;">内测资格</el-button>
        </el-col>
        <el-col :span="2" :offset="6">
          <el-button type="success" size="small" plain @click="showdetails()" :disabled="BtDisable.info"
                     style="font-size: 14px;">更改信息</el-button>
        </el-col>
      </el-row>
    </div>
    <div id="stepbar" class="container" v-if="MyInfo.showstep">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="更新信息" description="此信息为平安小助手代填写的信息，完成后点击下一步"></el-step>
        <el-step title="绑定平安账号" description="在此绑定报平安系统账号，便于小助手登录，账号为学号"></el-step>
        <el-step title="绑定邮箱" description="此邮箱用来接收小助手提示信息，每次成功或者失败的辅助都会发邮件通知"></el-step>
      </el-steps>
    </div>
    <div id="inputinfo" class="container" v-if="MyInfo.showdetail">
      <el-form :model="MyInfo" :rules="fieldRules" id="formb" ref="myform">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="name">
              <el-input type="text" placeholder="姓名" v-model="MyInfo.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="province">
              <el-input type="text" placeholder="省" v-model="MyInfo.province"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="city">
              <el-input type="text" placeholder="市" v-model="MyInfo.city"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="area">
              <el-input type="text" placeholder="区" v-model="MyInfo.area"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="phone">
          <el-input type="text" placeholder="手机号" v-model="MyInfo.phone"></el-input>
        </el-form-item>
        <el-form-item prop="urname">
          <el-input type="text" placeholder="紧急联系人" v-model="MyInfo.urname"></el-input>
        </el-form-item>
        <el-form-item prop="urphone">
          <el-input type="text" placeholder="紧急联系人手机号" v-model="MyInfo.urphone"></el-input>
        </el-form-item>
        <el-form-item prop="exectime">
          <el-time-select v-model="MyInfo.exectime" :picker-options="timeoptions" placeholder="选择报平安时间">
          </el-time-select>
        </el-form-item>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="3">
          <el-button type="info" size="small" plain @click="update()">{{BtText.upinfo}}</el-button>
        </el-col>
        <el-col :span="3" :offset="4">
          <el-button type="success" size="small" plain @click="autoupdate()">自动获取</el-button>
        </el-col>
        <el-col :span="3" :offset="4" v-if="BtDisable.start">
          <el-button type="primary" size="small" plain @click="start()">开启服务</el-button>
        </el-col>
      </el-row>
    </div>
    <div id="bindaccount" class="container" v-if="MyInfo.showinput">
      <h3 class="title" style="color: gray">账号绑定</h3>
      <el-form :model="MyInfo" :rules="accountRules" ref="accountform">
        <el-form-item prop="account">
          <el-input placeholder="报平安账号" v-model.number="MyInfo.account"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="text" placeholder="密码:身份证号" v-model="MyInfo.password"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" plain @click="binduser()">验证账号并绑定</el-button>
    </div>

    <div id="bindemail" class="container" v-if="MyInfo.showemail">
      <h3 class="title" style="color: gray">邮箱绑定</h3>
      <el-form :model="MyInfo" :rules="emailRules" ref="emailform">
        <el-form-item prop="email">
          <!--   对应了emailRules的 email-->
          <el-input type="text" placeholder="邮箱" v-model="MyInfo.email"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="MyInfo" :rules="veryfcodeRules" ref="veryfcodeform">
        <el-form-item prop="veryfcode">
          <el-input placeholder="验证码" v-model.number="MyInfo.veryfcode" style="width: 65%"></el-input>
          <el-button type="primary" size="small" plain @click="sendemail()" :loading="MyInfo.emailbutton">
            {{MyInfo.emailBtnWord}}
          </el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" plain @click="bindemail()">绑定</el-button>
    </div>

    <div id="topup" class="container" v-if="MyInfo.showtopup">
      <h3 class="title" style="color: gray">验证密钥</h3>
      <el-form :model="MyInfo" :rules="keysRules" ref="keysform">
        <el-form-item prop="keys">
          <el-input type="text" placeholder="密钥" v-model="MyInfo.keys"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" plain @click="topup()">验证</el-button>
    </div>

  </div>

</template>

<script>
  export default {
    data() {
      return {
        active: 0, finishinfo: false,
        MyInfo: {
          name: '', province: '', city: '', area: '', phone: '', urname: '', urphone: '', exectime: '', days: '0',
          account: '', password: '',
          keys: '',
          email: '', veryfcode: '', emailbutton: false, emailtimes: 61, emailBtnWord: '获取验证码',
          showinput: false, showtopup: false, showemail: false, showdetail: false, showstep: false
        },
        BtDisable: {
          pop: true,
          email: true,
          bind: true,
          topup: true,
          info: true,
          start:false  // 禁用 开启服务，在填入信息时
        },
        BtText: {
          upinfo: '更新信息'
        }
        ,
        timeoptions: {
          start: '08:30', step: '00:30', end: '17:00'
        }, fieldRules: {
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'},
            {
              pattern: /^([\u4e00-\u9fa5]{1,10}|[a-zA-Z.\s]{1,20})$/,
              message: '不超过十个中文，二十个英文',
              trigger: ['blur', 'change']
            }
          ], province: [
            {required: true, message: '请输入所在省', trigger: 'blur'},
            {pattern: /^[\u4e00-\u9fa5]{1,10}$/, message: '不超过十个中文', trigger: ['blur', 'change']}
          ], city: [
            {required: true, message: '请输入所在市', trigger: 'blur'},
            {pattern: /^[\u4e00-\u9fa5]{1,10}$/, message: '不超过十个中文', trigger: ['blur', 'change']}
          ], area: [
            {required: true, message: '请输入所在区', trigger: 'blur'},
            {pattern: /^[\u4e00-\u9fa5]{1,10}$/, message: '不超过十个中文', trigger: ['blur', 'change']}
          ], phone: [
            {required: true, message: '请输入联系电话', trigger: 'blur'},
            {pattern: /^[0-9]{11}$/, message: '格式为11位数字', trigger: ['blur', 'change']}
          ], urname: [
            {required: true, message: '请输入紧急联系人', trigger: 'blur'},
            {
              pattern: /^([\u4e00-\u9fa5]{1,10}|[a-zA-Z.\s]{1,20})$/,
              message: '不超过十个中文，二十个英文',
              trigger: ['blur', 'change']
            }
          ], urphone: [
            {required: true, message: '请输入紧急联系人电话', trigger: 'blur'},
            {pattern: /^[0-9]{11}$/, message: '格式为11位数字', trigger: ['blur', 'change']}
          ], exectime: [
            {required: true, message: '请输入执行时间', trigger: 'blur'}
          ],
        }, emailRules: {
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {type: 'email', message: '请输入正确格式的邮箱', trigger: ['blur', 'change']}
          ]
        }, veryfcodeRules: {
          veryfcode: [
            {required: true, message: '请输入验证码', trigger: 'blur'},
            {type: 'number', min: 99999, max: 999999, message: '请输入6位数字的验证码', trigger: ['blur', 'change']}
          ]
        }, accountRules: {
          account: [
            {required: true, message: '请输入报平安账号', trigger: 'blur'},
            {type: 'number', message: '请输入学号', trigger: ['blur', 'change']}
          ], password: [
            {required: true, message: '请输入报平安密码', trigger: 'blur'},
            {pattern: /^[A-Za-z0-9]{18}$/, message: '请输入身份证号', trigger: ['blur', 'change']}
            //  使用自定义函数 rulepassword 限制
          ],
        }, keysRules: {
          keys: [
            {required: true, message: '请输入内测秘钥', trigger: 'blur'},
            {pattern: /^[A-Za-z0-9]{8}$/, message: '请填入正确的内测秘钥', trigger: ['blur', 'change']}
          ]
        }
      }
    }, created() {
      this.initit()  // 初始化操作
      this.updateuserinfo()  // 自动刷新下方表格中的用户数据，如果存在
    },
    methods: {
      update() { // 用来绑定报平安信息
        this.$refs['myform'].validate((valid) => {
          if (valid) {
            let userInfo = {
              name: this.MyInfo.name,
              province: this.MyInfo.province,
              city: this.MyInfo.city,
              area: this.MyInfo.area,
              phone: this.MyInfo.phone,
              urname: this.MyInfo.urname,
              urphone: this.MyInfo.urphone,
              exectime: this.MyInfo.exectime
            }
            this.$api.user.postuserdata(userInfo).then((res) => {
              console.log(res)
              if (res.error != null) {
                this.$message({message: res.error, type: 'error'})
              } else {
                this.$message({message: res.msg, type: 'success'})
                if (!this.finishinfo) {
                  // 填写成功后，开始填写下一个
                  this.active = 1
                  this.MyInfo.showdetail = false
                  this.MyInfo.showinput = true
                }
              }
            }).catch((res) => {
              this.$message({message: res.message, type: 'error'})
            })
          } else {
            this.$message({message: '请检查填入数据', type: 'warning'})
            return false;
          }
        });
      }, autoupdate() {
        // 此接口 属于锦上添花，优先级低！
        this.$message({message: '开发人员奋力工作中', type: 'warning'})
      }, start() {
        this.$api.user.dostart().then((res) => {
          if (res.error != null) {
            this.$message({message: '启动失败：' + res.error, type: 'error'})
          } else {
            const sh = this.$createElement;
            this.$notify({
              title: '提示',
              message: sh('i', {style: 'color: green'},
                '开启成功！ 注意，如果当前时间已超过所设置的时间，助手表示无能为力，请今日自行报平安'),
              duration: 0
            });
          }
        }).catch((res) => {
          this.$message({message: res.message, type: 'error'})
        })
      }, pop() {
        this.$api.user.dogetdays().then((res) => {
          if (res.error != null) {
            this.$message({message: res.error, type: 'error'})
            this.MyInfo.days = '未知'
          } else {
            this.MyInfo.days = res.days
            const h = this.$createElement;
            this.$notify({
              title: '剩余天数',
              message: h('i', {style: 'color: skyblue'}, '当前用户剩余的自动报平安天数是：' + this.MyInfo.days),
            });
          }
        }).catch((res) => {
          this.$message({message: res.message, type: 'error'})
        })
      }, initit() {
        this.$api.user.dochkinfo().then((res) => {
          if (res.miss === 'None') {
            this.unlockbt()  // 解锁所有按钮
            this.pop()  // 检查通过 提示时间
            this.MyInfo.showdetail = true
            this.finishinfo = true
          } else if (res.miss === 'di') {
            this.MyInfo.showstep = true
            this.active = 0
            this.MyInfo.showdetail = true
            this.BtText.upinfo = '下一步'
          } else if (res.miss === 'account') {
            this.MyInfo.showstep = true
            this.active = 1  // 关闭详细信息填写
            this.MyInfo.showinput = true  // 关闭账号信息绑定
          } else {
            this.MyInfo.showstep = true
            this.active = 2  // 进入输入邮箱页面
            this.MyInfo.showemail = true  // 开启邮箱信息绑定
          }
        }).catch((res) => {
          this.$message({message: res.message, type: 'error'})
        })
      }, showbind() {
        this.hiddenall()
        this.MyInfo.showinput = !this.MyInfo.showinput;
      }, showtopup() {
        this.hiddenall()
        this.MyInfo.showtopup = !this.MyInfo.showtopup;
      }, showemail() {
        this.hiddenall()
        this.MyInfo.showemail = !this.MyInfo.showemail;
      }, showdetails() {
        console.log('showde')
        this.hiddenall()
        this.MyInfo.showdetail = !this.MyInfo.showdetail;
      }, unlockbt() { // 解锁所有按钮
        this.BtDisable.bind = false
        this.BtDisable.email = false
        this.BtDisable.info = false
        this.BtDisable.pop = false
        this.BtDisable.topup = false
        this.BtDisable.start = true // 解锁后，即可开启服务
      }, binduser() {
        this.$refs['accountform'].validate((valid) => {
          if (valid) {
            let accountInfo = {
              account: this.MyInfo.account,
              password: this.MyInfo.password
            }
            this.$api.user.dobindaccount(accountInfo).then((res) => {
              console.log(res)
              if (res.error != null) {
                this.$message({message: res.error, type: 'error'})
              } else if (res.success === "yes") {
                this.$message({message: "绑定账号成功", type: 'success'})
                if (!this.finishinfo) {
                  this.MyInfo.showinput = false; // 绑定成功后隐藏窗口
                  this.active = 2 //开始绑定邮箱
                  this.MyInfo.showemail = true // 显示绑定邮箱窗口
                }
              } else if (res.success === "no") {
                this.$message({message: "绑定账号失败，请稍后重试或者检查密码", type: 'warning'})
              }
            }).catch((res) => {
              this.$message({message: res.message, type: 'error'})
            })
          } else {
            this.$message({message: '请验证格式是否正确', type: 'warning'})
            return false;
          }
        });
      },
      topup() {
        this.$refs['keysform'].validate((valid) => {
          if (valid) {
            let info = {
              cdk: this.MyInfo.keys
            }
            this.$api.user.dotopup(info).then((res) => {
              console.log(res)
              if (res.error != null) {
                this.$message({message: res.error, type: 'error'})
              } else if (res.success === "yes") {
                this.$message({message: "内测资格，添加:" + res.capacity + "天成功！", type: 'success'})
                this.MyInfo.showtopup = false
              } else if (res.success === "no") {
                this.$message({message: "使用失败，请检查密钥", type: 'warning'})
              }
            }).catch((res) => {
              this.$message({message: res.message, type: 'error'})
            })
          } else {
            this.$message({message: '请检查秘钥是否正确', type: 'warning'})
            return false;
          }
        });
      },
      updateuserinfo() {
        this.$api.user.getuserdata().then((res) => {
          console.log(res)
          if (res.error != null) {
            // 这里不警告了
          } else {
            this.MyInfo.name = res.msg.name
            this.MyInfo.province = res.msg.province
            this.MyInfo.city = res.msg.city
            this.MyInfo.area = res.msg.area
            this.MyInfo.phone = res.msg.phone
            this.MyInfo.urname = res.msg.urname
            this.MyInfo.urphone = res.msg.urphone
            this.MyInfo.exectime = res.msg.exectime
          }
        }).catch((res) => {
          this.$message({message: res.message, type: 'error'})
        })
      },
      sendemail() {
        this.$refs['emailform'].validate((valid) => {
          if (valid) {
            let emailInfo = {
              email: this.MyInfo.email
            }
            this.$api.user.dosendemail(emailInfo).then((res) => {
              console.log(res)
              if (res.error != null) {
                this.$message({message: res.error, type: 'error'})
              } else if (res.success === "yes") {
                this.$message({message: "邮件发送成功，请检查邮箱（或者垃圾邮件栏）", type: 'success'})
                let that = this.MyInfo
                let timer = setInterval(function () {
                  if (that.emailtimes > 1) {
                    that.emailbutton = true
                    that.emailtimes--
                    that.emailBtnWord = `${that.emailtimes}s`
                  } else {
                    clearInterval(timer)
                    that.emailBtnWord = '获取验证码'
                    that.emailbutton = false
                    that.emailtimes = 61
                  }
                }, 1000)
              } else if (res.success === "no") {
                this.$message({message: "邮件发送失败，请稍后重试", type: 'warning'})
              }
            }).catch((res) => {
              this.$message({message: res.message, type: 'error'})
            })
          } else {
            this.$message({message: '请检查邮箱格式', type: 'warning'})
            return false;
          }
        });

      },
      bindemail() {
        this.$refs['veryfcodeform'].validate((valid) => {
          if (valid) {
            let emailInfos = {
              email: this.MyInfo.email,
              code: this.MyInfo.veryfcode
            }
            this.$api.user.dobindemail(emailInfos).then((res) => {
              console.log(res)
              if (res.error != null) {
                this.$message({message: res.error, type: 'error'})
              } else if (res.success === "yes") {
                this.$message({message: "绑定邮箱成功", type: 'success'})
                if (!this.finishinfo) {
                  this.MyInfo.showemail = false  // 绑定成功自动隐藏
                  this.MyInfo.showstep = false
                  this.MyInfo.showdetail = true
                  this.unlockbt()  //解锁所有按钮
                }
              } else if (res.success === "no") {
                this.$message({message: "绑定邮箱失败，请确认验证码", type: 'warning'})
              }
            }).catch((res) => {
              this.$message({message: res.message, type: 'error'})
            })
          } else {
            this.$message({message: '请检查验证码格式', type: 'warning'})
            return false;
          }
        });
      },
      hiddenall() {
        this.MyInfo.showinput = false
        this.MyInfo.showtopup = false
        this.MyInfo.showemail = false
        this.MyInfo.showdetail = false
      },
    }
  }
</script>

<style scoped lang="scss">

  #inputinfo {
    width: 85%;
    height: 430px;

    #formb {
      .el-input {
        width: 100%;
      }
    }
  }

  #stepbar {
    width: 85%;
    height: 200px;
  }

  #bindaccount {
    width: 60%;
    text-align: center;
    height: 240px;


    .el-input {
      padding-bottom: 10px;
      width: 100%;
    }
  }

  #bindemail {
    width: 90%;
    height: 220px;
    text-align: center;
  }

  #userinfo {
    width: 82%;
    height: 330px;
  }

  #topup {
    width: 50%;
    text-align: center;
    height: 180px;

    .el-input {
      width: 100%;
      margin-bottom: 10px;
    }
  }

  .container {
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    margin: 30px auto;
    width: 300px;
    height: 300px;
    padding: 35px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;

    .title {
      margin: 0 auto 30px auto;
      text-align: center;
      color: #505458;
    }
  }

</style>
